package com.sunjob.loginserver.service;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import com.sunjob.common.domain.img.SysImg;
import com.sunjob.common.domain.loginServer.SysDept;
import com.sunjob.common.domain.loginServer.SysRole;
import com.sunjob.common.domain.loginServer.SysUser;
import com.sunjob.common.result.Result;
import com.sunjob.common.util.MROUtils;
import com.sunjob.loginserver.mapper.SysUserMapper;
import com.sunjob.loginserver.otherService.ImgService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.shiro.crypto.hash.Md5Hash;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.regex.Pattern;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Wangzurong
 * @create 2022-07-25 10:45
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    DeptService deptService;
    @Autowired
    ImgService imgService;
    @Autowired
    RoleService roleService;

    @Override
    public boolean login(String username, String password) {
        SysUser user = sysUserMapper.getUserByLoginName(username);
        if (user == null) {
            return false;
        }
        String pwd = user.getPassword();
        Md5Hash md5Hash = new Md5Hash(username + password + user.getSalt());
        String s = md5Hash.toHex();
        if (s != null && s.equals(pwd)) {
            StpUtil.login(user.getUserId());
            // 加载角色列表
            StpUtil.getRoleList();
            // 加载权限列表
            StpUtil.getPermissionList();
            // 获取职位列表
            List<String> posts = sysUserMapper.queryPostsByUserId(user.getUserId());
            // 获取tokenSession
            user.setPosts(posts);
            SaSession tokenSession = StpUtil.getTokenSession();

            SysDept sysDept = deptService.queryDeptByUserId(user.getUserId());
            if (sysDept != null) tokenSession.set("deptInfo", sysDept);
            // 加载用户头像信息
            if (user.getAvatar() != null) {
                Result<SysImg> imgById = imgService.getImgById(Long.valueOf(user.getAvatar()));
                if (imgById.getData() != null) {
                    user.setAvatarUrl(imgById.getData().getAbImgUrl());
                }
            }
            tokenSession.set("userInfo", user);
            return true;
        }
        return false;
    }

    @Override
    public Integer batchLogout(List<Integer> ids) {
        int res = 0;
        for (int i = 0; i < ids.size(); i++) {
            try {
                StpUtil.logout(ids.get(i));
                res++;
            } catch (Exception e) {

            }
        }
        return res;
    }

    @Override
    public Integer getNumByLoginName(String loginName) {
        return sysUserMapper.getNumByLoginName(loginName);
    }

    @Override
    public Integer addUser(SysUser user) {
        if (getNumByLoginName(user.getLoginName()) >= 1) {
            return 0;
        }
        user.setDelFlag(0);
        user.setStatus(0);
        user.setCreateBy("alone");
        user.setUpdateBy("alone");
        LocalDateTime now = LocalDateTime.now();
        user.setCreateTime(now);
        user.setUpdateTime(now);
        user.setSalt("111111");
        user.setSex("0");
        user.setUserType("00");
        // 随机用户名
        user.setUserName(UUID.randomUUID().toString().replaceAll("-", "").substring(0, 6));
        // 加密密码
        user.setUserId(MROUtils.nextId());
        // 添加默认角色
        Integer i = roleService.addRole(user.getUserId(), 2);
        if (i == 0) {
            return 0;
        }
        String pwd = user.getPassword();
        Md5Hash md5Hash = new Md5Hash(user.getLoginName() + pwd + user.getSalt());
        String s = md5Hash.toHex();
        user.setPassword(s);
        return sysUserMapper.insertUser(user);
    }

    @Override
    public Result<Boolean> udpateUser(SysUser user) {
        // 设置更新时间
        user.setUpdateTime(LocalDateTime.now());
        SaSession tokenSession = StpUtil.getTokenSession();
        // 设置更新者
        SysUser userInfo = (SysUser) tokenSession.get("userInfo");
        user.setUpdateBy(userInfo.getLoginName());
        // 设置id
        user.setUserId(userInfo.getUserId());
        // 进行格式判断
        if (user.getPhonenumber() != null && user.getPhonenumber().trim().length() != 0) {
            if (!Pattern.matches("^[1]{1}[3457]{1}[0-9]{9}$", user.getPhonenumber())) {
                return Result.fail("手机号格式错误，请重新输入");
            }
            // 手机号唯一判断
            SysUser user1 = sysUserMapper.getUserByPhone(user.getPhonenumber());
            if (user1 != null && (!user1.getUserId().equals(user.getUserId()))) {
                return Result.fail("手机号已被使用，请重新输入");
            }
        }
        if (user.getUserName() != null && user.getUserName().trim().length() != 0) {
            // 进行判断
            SysUser user1 = sysUserMapper.getUserByUserName(user.getUserName());
            if (user1 != null && (!user1.getUserId().equals(user.getUserId()))) {
                return Result.fail("用户名已被使用，请重新输入");
            }
        }
        if (user.getEmail() != null && user.getEmail().trim().length() != 0) {
            if (!Pattern.matches("^[0-9a-zA-Z]+@[0-9a-zA-Z]+\\.com", user.getEmail())) {
                return Result.fail("邮箱格式有误，请重新输入");
            }
            SysUser user1 = sysUserMapper.getUserByEmail(user.getEmail());
            if (user1 != null && (!user1.getUserId().equals(user.getUserId()))) {
                return Result.fail("邮箱已被使用，请重新输入");
            }
        }
        if (user.getSex() != null && user.getSex().trim().length() != 0) {
            if ((!user.getSex().equals("1")) && (!user.getSex().equals("0"))) {
                return Result.fail("输入了错误的性别,请重新输入");
            }
        }
        Integer i = sysUserMapper.updateUser(user);
        if (i == 0) {
            return Result.fail("更新用户失败");
        } else {
            //刷新缓存
            tokenSession.set("userInfo", sysUserMapper.getUserById(user.getUserId()));
            return Result.ok(true, "更新用户成功");
        }
    }

    @Override
    public boolean loginMulti(String name, String pwd, String terminal) {
        SysUser user = sysUserMapper.getUserByLoginName(name);
        if (user == null) {
            return false;
        }
        String pwd1 = user.getPassword();
        Md5Hash md5Hash = new Md5Hash(name + pwd + user.getSalt());
        String s = md5Hash.toHex();
        if (s != null && s.equals(pwd1)) {
            StpUtil.login(user.getUserId(), terminal);
            if ("pc".equals(terminal)) {
                // pc端
                StpUtil.renewTimeout(30 * 60 * 60);
            }
            // 加载角色列表
            StpUtil.getRoleList();
            // 加载权限列表
            StpUtil.getPermissionList();
            // 获取职位列表
            List<String> posts = sysUserMapper.queryPostsByUserId(user.getUserId());
            // 获取tokenSession
            user.setPosts(posts);
            SaSession tokenSession = StpUtil.getTokenSession();
            SysDept sysDept = deptService.queryDeptByUserId(user.getUserId());
            if (sysDept != null) tokenSession.set("deptInfo", sysDept);
            // 加载用户头像信息
            if (user.getAvatar() != null) {
                Result<SysImg> imgById = imgService.getImgById(Long.valueOf(user.getAvatar()));
                if (imgById.getData() != null) {
                    user.setAvatarUrl(imgById.getData().getAbImgUrl());
                }
            }
            tokenSession.set("userInfo", user);
            return true;
        }
        return false;
    }

    @Override
    public SysImg udpateAvatar(Long loginId, SysImg sysImg) {
        // 修改用户avatar 连接图片服务器
        Result<SysImg> sysImgResult = imgService.pushImg(sysImg);
        if (sysImgResult.getData() == null) {
            return null;
        }
        Long imgId = sysImgResult.getData().getImgId();
        sysImgResult.getData().setData(null);
        //
        Integer i = sysUserMapper.updateAvatar(loginId, imgId);
        if (i == 0) {
            return null;
        }
        return sysImgResult.getData();
    }


}
